<style>
	@import "/static/css/common.css";
	@import "/static/css/chat-chating.css";
</style>
<template>
	<view>
		<view class="classreturn chat_conttit">
			<view class="content">
				<view class="ds-in-bl return"> </view>
				<view class="ds-in-bl search center"><span>{{friend.name}}</span></view>
				<view class="ds-in-bl menu">
					<span class="close-button"><span class="iconfont icon-close"></span></span>
				</view>
			</view>
		</view>
		<view class="chatInterface">
			<view class="chat-container">
				<scroll-view :scroll-top="scrollTop" scroll-y="true" class="chat-container-scroll"
					show-scrollbar="false">
					<view class="clear" v-for="(message, key) in chatMessages" :key="key"
						:class="message.userid === user.userid ? 'self chat-scroll__item' : 'chat-scroll__item'">
						<view class="chat-scroll__item__avatar offline-gray">
							<image :src="getUserAvatar(message.userid)" mode="aspectFill"></image>
						</view>
						<view class="chat-scroll__item__message">
							{{ message.content }}
						</view>
					</view>
					<view class="lastClear"></view>
				</scroll-view>
			</view>
			<view class="send-box">
				<input placeholder="请输入内容" class="send-box__input" v-model="content">
				<span class="send-box__btn" @click="sendMessage">发送</span>
			</view>
		</view>
		<view v-if="tip" class="tip-layer">
			<view class="tip">{{tipContent}}</view>
		</view>
	</view>
</template>

<script>
	import {
		showTips
	} from '@/static/js/common.js';

	export default {
		data() {
			return {
				WebSocketUrl: "wss://www.fengjian123.com/service9502/",
				httpUrl: "https://www.fengjian123.com/service9501/",
				imgUrl: "https://www.fengjian123.com/",
				// WebSocketUrl: "ws://192.168.200.128:9502/",
				// httpUrl: "http://192.168.200.128:9501/",
				socketOpen: false,
				content: '',
				token: "",
				friend: {
					name: "",
					userid: "",
					avatar: "",
				},
				user: {
					userid: "",
					avatar: ''
				},
				chatMessages: [],
				scrollTop: 0,
				tipContent: '',
				tip: 0,
				timestamp: new Date().getTime(),
			}
		},
		// 页面加载时触发
		onLoad(option) {
			this.getCookie();
		},
		//页面断开时触发
		onUnload() {
			this.close();
		},
		// 页面渲染结束后触发
		mounted() {
			this.$nextTick(() => {
				this.getChat();
				this.connect();
				this.scrollToBottom();
			});
		},
		// 监听数据"chatMessages"的变化，当数据变化时，执行相应的操作
		watch: {
			chatMessages() { //监听消息，滚动到对应位置
				this.scrollTop = this.scrollTop + 1;
			}
		},
		methods: {
			// 连接服务端
			connect: function() {
				let _this = this;
				console.log("开始连接..." + "用户id：" + _this.user.userid + "用户token：" + _this.token + "朋友id：" + _this.friend
					.userid);
				uni.connectSocket({ // 创建一个 WebSocket 连接
					url: _this.WebSocketUrl + "?userId=" + _this.user.userid + "&friendId=" + _this.friend
						.userid,
					method: 'POST'
				});
				uni.onSocketOpen(function(res) { // 连接websocket成功
					_this.socketOpen = true;
					console.log('WebSocket连接已打开！');
				});
				uni.onSocketError(function(res) { // 连接websocket失败
					console.log('WebSocket连接打开失败，请检查！');
				});
				uni.onSocketMessage(function(res) { // 监听WebSocket接受到服务器的消息事件，每当有消息发送，就会触发此方法
					let content = res.data;
					let data = JSON.parse(content);
					console.log(data);
					_this.pushChat(data);
				});
				uni.onSocketClose(function(res) {
					// _this.connect();
					console.log('WebSocket 已关闭！');
				});
			},
			//关闭服务端
			close: function() {
				uni.closeSocket();
			},
			//拉取聊天内容
			getChat: function() {
				let _this = this;
				uni.request({
					url: _this.httpUrl + 'chat/chat_get',
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'Authorization': 'Bearer ' + _this.token,
					},
					data: {
						userId: _this.user.userid,
						friendId: _this.friend.userid
					},
					success: (res) => {
						console.log(res.data.msg);
						if (res.data.err == 0) {
							_this.chatMessages = JSON.parse(res
								.data.chatList);
							_this.friend.name = res.data.friendInfo.nickname;
							_this.friend.avatar = res.data.friendInfo.avatar;
						} else {
							uni.reLaunch({
								url: '/pages/index/index',
							});
							// 账号密码版
							// _this.tips(res.data.msg);
							// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)
						}
					},
					fail: (res) => {
						console.log(res);
					},
				});
			},
			//点击按钮，发送消息
			sendMessage: function() {
				let _this = this;
				if (_this.content.trim() != "") {
					let message = {
						content: _this.content,
						userid: _this.user.userid,
						friendid: _this.friend.userid
					};
					_this.addChat(message); //插入数据库
				}
				_this.content = "";
			},
			//插入数据库
			addChat: function(message) {
				let messages = JSON.stringify(message);
				let _this = this;
				uni.request({
					url: _this.httpUrl + 'chat/chat_add',
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'Authorization': 'Bearer ' + _this.token,
					},
					data: {
						data: messages,
					},
					success: (res) => {
						console.log(res.data.msg);
						if (res.data.err == 0) {
							_this.sendSocketMessage(messages); //插入成功，再发送到websocket
						} else if (res.data.err == 1) {
							_this.tips(res.data.msg);
						} else {
							uni.reLaunch({
								url: '/pages/index/index',
							});
							// 账号密码版
							// _this.tips(res.data.msg);
							// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)
						}
					},
					fail: (res) => {
						console.log(res);
					},
				});
			},
			//发送消息到websocket
			sendSocketMessage: function(msg) {
				let _this = this;
				if (_this.socketOpen) {
					uni.sendSocketMessage({
						data: msg
					});
				} else {
					socketMsgQueue.push(msg);
				}
			},
			//获取send了的数据，增加到消息数组
			pushChat: function(data) {
				let _this = this;
				let message = {
					content: data.content,
					userid: data.userid,
					friendid: data.friendid,
				};
				_this.chatMessages.push(message);
			},
			//滚动到底部
			scrollToBottom: function() {
				let _this = this;
				setTimeout(() => {
					_this.scrollTop = 99999;
				}, 300);
			},
			getCookie: function() {
				let _this = this;
				uni.getStorage({
					key: 'cookie',
					success: function(res) {
						if (res.data.id && res.data.login) {
							console.log(res.data);
							_this.user.userid = res.data.id;
							_this.token = res.data.token;
							_this.user.avatar = res.data.avatar;
						} else {
							uni.reLaunch({
								url: '/pages/index/index',
							});
							// 账号密码版
							// _this.tips('登录失效，正在跳转...');
							// setTimeout(() => {uni.reLaunch({url: '/pages/login/index',});}, 1000)
						}
					},
					fail: function() {
						_this.toLogin();
						// uni.reLaunch({url: '/pages/login/index',});  // 账号密码版
					}
				});
				uni.getStorage({
					key: 'friendId',
					success: function(res) {
						if (res.data) {
							_this.friend.userid = res.data;
						} else {
							_this.tips('该好友不存在，正在跳转...');
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/chat/list',
								});
							}, 1000)
						}
					},
					fail: function() {
						uni.reLaunch({
							url: '/pages/chat/list',
						});
					}
				});
			},
			getUserAvatar(userid) {
				let _this = this;
				if (userid === _this.user.userid) {
					if (_this.user.avatar) {
						return `${_this.imgUrl}${_this.user.avatar}?t=${_this.timestamp}`;
					} else {
						return '/static/img/userAvatar.jpg';
					}
				} else {
					if (_this.friend.avatar) {
						return `${_this.imgUrl}${_this.friend.avatar}?t=${_this.timestamp}`;
					} else {
						return '/static/img/userAvatar.jpg';
					}
				}
			},
			tips: function(content) {
				showTips(this, content);
			},
		}
	}
</script>